#!/usr/bin/python
# -*- coding:utf-8 -*-
import sys
import os
picdir = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), 'pic')
libdir = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), 'lib')
if os.path.exists(libdir):
    sys.path.append(libdir)

from datetime import datetime
from datetime import timedelta
import socket
import random

festivallist = {
    '2021-02-12':'cnewyear',
    '2021-02-13':'cnewyear',
    '2021-02-14':'valent',
    '2021-02-15':'cnewyear',
    '2021-02-16':'cnewyear',
    '2021-02-17':'cnewyear',
    '2021-02-18':'cnewyear',
    '2021-02-26':'yuanxiao',
    '2021-04-01':'yurenjie',
    '2021-05-01':'laodong',
    '2021-06-01':'ertong',
    '2021-07-01':'jiandang',
    '2021-09-21':'zhongqiu',
    '2021-10-01':'guoqing',
    '2021-12-25':'chrismas',
    '2022-01-01':'newyear'
}

import logging
from waveshare_epd import epd2in13b_V3
import time
from PIL import Image,ImageDraw,ImageFont
import traceback

logging.basicConfig(level=logging.DEBUG)

try:
    logging.info("epd2in13b_V3 Demo")
    
    epd = epd2in13b_V3.EPD()
    logging.info("init and Clear")
    epd.init()
    #epd.Clear()
    
    now = datetime.now()
    today = now.strftime('%Y-%m-%d')
    if today in festivallist:
        special = festivallist.get(today)
    else:
        special = 'usual'
    
    bmpfiles = [os.path.splitext(x)[0] for x in os.listdir(picdir) if os.path.isfile(os.path.join(picdir,x)) and os.path.splitext(x)[1]=='.bmp']
    fileindex = [os.path.splitext(x)[0] for x in bmpfiles if os.path.splitext(x)[1]=='.b']

    #filename = random.sample(fileindex, 1)[0]
    fileindex = [x for x in fileindex if os.path.splitext(x)[0]==special]
    for num in list(range(now.minute)):
        random.shuffle(fileindex)
    filename = random.sample(fileindex, 1)[0]
    print(filename)

    Blackimage = Image.open(os.path.join(picdir, filename+'.b.bmp'))
    RYimage = Image.open(os.path.join(picdir, filename+'.ry.bmp'))
    epd.display(epd.getbuffer(Blackimage), epd.getbuffer(RYimage))

    #logging.info("Clear...")
    #epd.init()
    #epd.Clear()
    
    logging.info("Goto Sleep...")
    epd.sleep()
    time.sleep(3)
    epd.Dev_exit()

    if now.hour < 7:
        if (now.weekday() > 4) | (special != 'usual'):
            startuptime = now.replace(hour=12, minute=0, second=0, microsecond=0)
        else:
            startuptime = now.replace(hour=19, minute=0, second=0, microsecond=0)
    else:
        if (now.minute < 25) | (now.minute > 50):
            startuptime = (now + timedelta(minutes=30)).replace(minute=30, second=0, microsecond=0)
        else:
            startuptime = (now + timedelta(hours=1)).replace(minute=0, second=0, microsecond=0)
    
    # 发送定时启动信息
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect(('127.0.0.1', 8423))
    s.send(('rtc_alarm_set ' + startuptime.strftime('%Y-%m-%dT%H:%M:%S+08:00') + ' 127').encode('ascii'))
    s.close()

except IOError as e:
    logging.info(e)
    
except KeyboardInterrupt:    
    logging.info("ctrl + c:")
    epd2in13b_V3.epdconfig.module_exit()
    exit()